<template>
  <el-upload
    class="avatar-uploader"
    action="/jeecg-boot/jx/imageUpload/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="image.url" :src="image.url" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { ref, reactive} from 'vue'
import { ElMessage } from 'element-plus'

// 会被mockjs影响而报错，所以本地测试上传时要关闭mockjs
const props = defineProps(['imageUrl'])
const image = reactive({
  url: props.imageUrl,
  resultName: '',
})

const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  image.url = URL.createObjectURL(uploadFile.raw)
  image.resultName = response.result.fileName;
}

const beforeAvatarUpload = (rawFile) => {
  // if (/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name) ) {
    // console.log(rawFile);
  // }
  if (!rawFile.type.includes('image')) {
    ElMessage.error('请上传正确的图片文件')
    return
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能大于2MB!')
    return false
  }
  return true
}

// 对外暴露数据
defineExpose({
  image: image,
});

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
